import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userLoginAPI, userInfoAPI, userLogoutAPI } from '@/api/user/index'
import { setToken, getToken, removeToken } from '@/utils/token'
// 引入路由
import { constantRoutes, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'

export const useUserStore = defineStore('User', () => {
  const token = ref('') // 用户唯一标识token

  const username = ref('')

  const avatar = ref('')

  const menuRoutes = ref(constantRoutes) // 仓库存储生成菜单需要数组(路由)

  const buttons = ref([]) // 存储用户是否拥有某个按钮

  token.value = getToken()

  // 用户登录方法
  const userLogin = async (data) => {
  // const userLogin = () => {
    // 登录请求
    // let res = await userLoginAPI(data)

    // 接口请求失败，进行手动数据设置
    let res = {
      code: 200,
      message: 'ok',
      ok: true,
      data: '123'
    }

    // 登录请求：成功200 -> token
    // 登录请求：失败201 ->
    if (res.code === 200) {
      // pinia仓库存储token
      // 由于pinia|vuex存储数据使用的js对象
      token.value = res.data
      setToken(res.data)
      return 'ok'
    } else {
      return Promise.reject(new Error(res.data))
    }
  }

  // 用于过滤当前用户需要展示的异步路由
  function filterAsyncRoute (asyncRoute, routes) {
    return asyncRoute.filter(item => {
      // console.log(routes.includes(item.name))
      if(routes.includes(item.name)) {
        if(item.children && item.children.length > 0) {
          // 硅谷333账号：product/trademark/attr/sku
          // console.log(item.children)
          item.children = filterAsyncRoute(item.children, routes)
        }
        return true
      }
    })
  }

  // 获取用户信息
  const getUserInfo = async () => {
    // let res = await userInfoAPI()
    let res = {
      code: 200,
      message: 'ok',
      ok: true,
      data: {
        routes: ['Product', 'SPU', 'SKU', 'TradeMark','Attr', 'Acl', 'Permission', 'User', 'Role'],
        buttons: [],
        roles: [],
        name: 'admin',
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
      }
    }
    if (res.code === 200) {
      username.value = res.data.name
      avatar.value = res.data.avatar
      buttons.value = res.data.buttons
      // 计算当前用户需要展示的异步路由
      let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute), res.data.routes)
      // 当前菜单的新数据
      menuRoutes.value = [...constantRoutes, ...userAsyncRoute, ...anyRoute]
      // 动态添加新的路由:目前路由器管理的只有常量路由，用户计算完毕异步路由、任意路由，动态追加
      let allAsyncRoutes = [...userAsyncRoute, ...anyRoute]
      allAsyncRoutes.forEach(route => {
        router.addRoute(route)
      })
      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }

  // 退出登录方法
  const userLogout = async () => {
    // 目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
    // mock接口转换为真实接口
    let res = await userLogoutAPI()
    if (res.code === 200) {
      token.value = ''
      username.value = ''
      avatar.value = ''
      removeToken()
      return 'ok'
    } else {
      return Promise.reject(new Error(res.message))
    }
  }

  return {
    token,
    username,
    avatar,
    userLogin,
    menuRoutes,
    getUserInfo,
    userLogout,
    buttons
  }
})
